package com.bookstore.bauhinia.book.controller;

import com.bookstore.bauhinia.pojo.Book;
import com.bookstore.bauhinia.pojo.CommonResult;
import com.bookstore.bauhinia.book.service.BookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class BookController {
    @Resource
    private BookService bookService;

    @PostMapping("/book/insert")
    public CommonResult insertBook(@RequestBody Book record) {
        int result = bookService.insert(record);
        System.out.println("*****插入结果:" + result);
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功", record);
        } else {
            return new CommonResult(444, "插入数据库失败", null);
        }
    }

    @GetMapping("/book/get/{id}")
    public CommonResult getBookById(@PathVariable("id") int id) {
        Book book = bookService.selectByPrimaryKey(id);
        System.out.println("*****查询结果:" + book);
        if (book != null) {
            return new CommonResult(200, "查询成功", book);
        } else {
            return new CommonResult(444, "没有对应记录,查询id:" + id, null);
        }
    }

    @GetMapping("/book/delete/{id}")
    public CommonResult deleteBookById(@PathVariable("id") int id) {
        int result = bookService.deleteByPrimaryKey(id);
        if (result > 0) {
            return new CommonResult(200, "删除数据成功");
        } else {
            return new CommonResult(444, "删除数据失败");
        }
    }

    @PostMapping("/book/update")
    public CommonResult updateBook(@RequestBody Book record) {
        int result = bookService.updateByPrimaryKey(record);
        if (result > 0) {
            return new CommonResult(200, "更新数据成功", record);
        } else {
            return new CommonResult(444, "更新数据失败", null);
        }
    }

    @GetMapping("/book/all")
    public CommonResult getAllBook(){
        List<Book> books = bookService.getAllBooks();
        if(books != null){
            return new CommonResult(200, "查询数据成功", books);
        } else {
            return new CommonResult(444, "查询数据失败", null);
        }
    }

    @GetMapping("/book/getByCategoryId/{category}")
    public CommonResult getBookByCategoryId(@PathVariable Integer category){
        List<Book> books = bookService.getBooksByCategoryId(category);
        if(books != null){
            return new CommonResult(200, "查询数据成功", books);
        } else {
            return new CommonResult(444, "查询数据失败", null);
        }
    }
}
